<script setup lang="ts">
import {nextTick, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox, type UploadProps} from 'element-plus'
import {BASE_URL} from "/@/utils/config";
import {Plus} from "@element-plus/icons-vue";
import { StarFilled } from '@element-plus/icons-vue'
import {useAgentApi} from '/@/api/judicial/agent';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量
const ruleFormRef = ref(null);
const state = reactive({
	ruleForm: {
		avatar: '',
		username: '',
		agent_name: '',
		password: '',
		data_total: 0,
		repeat_password: '',
		name: '',
		price: '',
		image_url: '',
	},
	dialog: {
		loading: false,
		type: '',
		isShowDialog: false,
		title: '',
		submitTxt: '',
	}
});

// 图片尺寸限制
const beforeUpload = (file: any) => {
	const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt500KB = file.size / 1024 / 1024 > 2;

	if (!isJPGorPNG) {
		ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
		return false;
	}
	if (isLt500KB) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		return false;
	}
}

const handleCoverSuccess: UploadProps['onSuccess'] = (
	response
) => {
	state.ruleForm.avatar = response.data.url
}

// 图片尺寸限制
const beforeUpload2 = (file: any) => {
	const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt500KB = file.size / 1024 / 1024 > 2;

	if (!isJPGorPNG) {
		ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
		return false;
	}
	if (isLt500KB) {
		ElMessage.error('上传图片大小不能超过 2MB!');
		return false;
	}
}

const handleCoverSuccess2: UploadProps['onSuccess'] = (
	response
) => {
	state.ruleForm.image_url = response.data.url
}

const rules = reactive ({
	username: [
		{ required: true, message: '请填写代理账号', trigger: 'blur' },
	],
	avatar: [
		{ required: true, message: '请上传代理头像', trigger: 'blur' },
	],
	nickname: [
		{ required: true, message: '请填写代理昵称', trigger: 'blur' },
	],
	agent_name: [
		{ required: true, message: '请填写代理名称', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请填写密码', trigger: 'blur' },
	],
	data_total: [
		{ required: true, message: '请填写数据条数', trigger: 'blur' },
	],
	repeat_password: [
		{ required: true, message: '请重复填写密码', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value!== state.ruleForm.password) {
					callback(new Error('两次填写的密码不一致!'));
				} else {
					callback();
				}
			}
		}
	],
	name: [
		{ required: true, message: '请填写产品名称', trigger: 'blur' },
	],
	price: [
		{ required: true, message: '请填写价格', trigger: 'blur' },
	],
	image_url: [
		{ required: true, message: '请上传产品图片', trigger: 'blur' },
	]
})

const submitForm = () => {
	ruleFormRef.value.validate((valid, fields) => {
		if (valid) {
			useAgentApi().agentFormSubmit(state.ruleForm).then((res) => {
				if (res.code == 200) {
					ElMessage.success(res.message);
					closeDialog();
				} else {
					ElMessage.error(res.message);
				}
            })
		} else {
			console.log('error submit!', fields)
		}
	})
};

// 打开弹窗
const openDialog = (type, row) => {
	if (type == 'add') {
		state.dialog.type = 'add';
		state.dialog.title = '添加代理';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		nextTick(() => {
			ruleFormRef.value.resetFields();
		});
	} else {
		state.dialog.type = 'edit';
		state.dialog.title = '代理操作';
		state.dialog.submitTxt = '修 改';
		state.ruleForm = row;
		state.ruleForm.agent_name = state.ruleForm.software.name;
		state.ruleForm.name = state.ruleForm.product.name;
		state.ruleForm.price = state.ruleForm.product.price;
		state.ruleForm.image_url = state.ruleForm.product.image_url;
	}
	state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
	ruleFormRef.value.resetFields();
	state.ruleForm = {
		avatar: '',
		username: '',
		agent_name: '',
		data_total: '',
		password: '',
		repeat_password: '',
		name: '',
		price: '',
		image_url: '',
	};
	emit('refresh');
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<template>
	<view class="system-user-dialog-container">
		<el-dialog @close="closeDialog" :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="700px">
			<el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="100px" status-icon class="demo-ruleForm">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="代理账号" prop="username">
							<el-input v-model="state.ruleForm.username" :disabled="state.dialog.type == 'edit'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="代理名称" prop="nickname">
							<el-input v-model="state.ruleForm.nickname"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="代理头像" prop="avatar">
							<el-upload
								v-model="state.ruleForm.avatar"
								class="avatar-uploader"
								:action="BASE_URL + 'lxs/upload/upload_file'"
								:data="{name: 'avatar'}"
								:show-file-list="false"
								:before-upload="beforeUpload"
								:on-success="handleCoverSuccess"
							>
								<img v-if="state.ruleForm.avatar" :src="state.ruleForm.avatar" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
							</el-upload>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="对应主体" prop="agent_name">
							<el-input v-model="state.ruleForm.agent_name"></el-input>
						</el-form-item>
						<el-form-item label="数据条数" prop="data_total">
							<el-input v-model="state.ruleForm.data_total" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type == 'add'">
						<el-form-item label="代理密码" prop="password">
							<el-input type="password" v-model="state.ruleForm.password" placeholder="请输入代理密码" clearable show-password></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type == 'add'">
						<el-form-item label="重复密码" prop="repeat_password">
							<el-input type="password" v-model="state.ruleForm.repeat_password" placeholder="请输入" clearable show-password></el-input>
						</el-form-item>
					</el-col>

					<el-divider>
						<el-icon><star-filled /></el-icon>
					</el-divider>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产品名称" prop="name">
							<el-input v-model="state.ruleForm.name"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产品价格" prop="price">
							<el-input type="number" v-model="state.ruleForm.price"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产品封面" prop="avatar">
							<el-upload
								v-model="state.ruleForm.image_url"
								class="avatar-uploader"
								:action="BASE_URL + 'lxs/upload/upload_file'"
								:data="{name: 'avatar'}"
								:show-file-list="false"
								:before-upload="beforeUpload2"
								:on-success="handleCoverSuccess2"
							>
								<img v-if="state.ruleForm.image_url" :src="state.ruleForm.image_url" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="submitForm" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</view>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
	width: 80px;
	height: 80px;
	display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 80px;
	height: 80px;
	text-align: center;
}
</style>